package com.dlc.felear.xiaoensale.activity;

import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ListView;

import com.dlc.felear.xiaoensale.R;
import com.dlc.felear.xiaoensale.adapter.EmnuControltemAdapter;
import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.customView.ConfirmDialog;
import com.dlc.felear.xiaoensale.customView.LoadingDialog;
import com.dlc.felear.xiaoensale.dao.CookingMenuDao;
import com.dlc.felear.xiaoensale.deviceUtil.TopbarHelper;
import com.dlc.felear.xiaoensale.entity.CookingMenu;
import com.dlc.felear.xiaoensale.helper.JsonHelper;
import com.dlc.felear.xiaoensale.helper.ThreadPoolExecutorHelper;
import com.dlc.felear.xiaoensale.utils.HandleSocketDataUtil;
import com.dlc.felear.xiaoensale.utils.NumToStringUtil;
import com.itdlc.android.library.base.BaseActivity;

import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

/**
 * 本地菜谱管理（删除 上传）
 */
public class EmnuControlActivity extends BaseActivity implements ConfirmDialog.ConfirmDialogCallback {

    private static final String TAG = "EmnuControlActivity";
    private TopbarHelper topbarHelper;
    @BindView(R.id.lv)
    ListView lv;
    private CookingMenuDao cookingMenuDao;
    private EmnuControltemAdapter adapter;
    private ConfirmDialog confirmDialog;
    private Handler handler;
    private LoadingDialog loadingDialog;
    private HashMap<Integer, View> tempMap = new HashMap<>();
    private int flag = 0;
    private int total = 0;
    private int index = 0;


    @Override
    protected int getLayoutRes() {
        return R.layout.activity_emnu_control;
    }

    @Override
    protected void initData() {
        cookingMenuDao = new CookingMenuDao(this);
        topbarHelper = new TopbarHelper(this);
        topbarHelper.setTitle("菜谱管理");
        topbarHelper.setNavActivity(LoadDataActivity.class);
        topbarHelper.setcon(R.drawable.arrow_left);
        adapter = new EmnuControltemAdapter(this);
        confirmDialog = new ConfirmDialog(this, this);
        lv.setAdapter(adapter);
        adapter.setItems(getWscMenu());
        tempMap.put(R.id.tv_wsh, findViewById(R.id.tv_wsh));
    }

    @Subscriber(tag = Constant.EVENT_NOTIFY_CONFIG_CHANGE)
    public void recieveAction(String msg) {
        try {
            showLongToast("上传成功");
            resetData();
        } catch (Exception e) {

        }
    }

    public void clickView(View view) {
        switch (view.getId()) {
            case R.id.tv_wsh:
                setViewBg(view);
                flag = 0;
                resetData();
                break;
            case R.id.tv_qbsc:
                confirmDialog.showDialog("是否删除全部菜谱", view.getId());
                break;
            case R.id.tv_bzcp:
                setViewBg(view);
                flag = 1;
                resetData();
                break;
            case R.id.tv_lscp:
                setViewBg(view);
                flag = 2;
                resetData();
                break;
        }
    }

    private void resetData() {
        if (flag == 0) {
            adapter.setItems(getWscMenu());
        } else if (flag == 1) {
            adapter.setItems(getMenu(Constant.MENU_STD));
        } else if (flag == 2) {
            adapter.setItems(getMenu(Constant.MENU_NORMAL));
        }
    }

    @Subscriber(tag = "sendMenuInfo")
    private void recieveChangeData(String msg) {
        Log.e(TAG, msg);
        handler.sendEmptyMessageDelayed(12221, 2000);
        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog(this, "正在删除数据...");
        }
        loadingDialog.show("正在刷新数据...");
    }

    private void setViewBg(View view) {

        if (!tempMap.containsKey(view.getId())) {
            tempMap.put(view.getId(), view);
        }
        for (Integer resId : tempMap.keySet()) {
            View view1 = tempMap.get(resId);
            if (view.getId() == resId) {
                view1.setBackgroundColor(Color.parseColor("#0000ff"));
            } else {
                view1.setBackgroundColor(Color.parseColor("#cccccc"));
            }
        }
    }

    private List<CookingMenu> getWscMenu() {
        List<CookingMenu> temp = cookingMenuDao.queryForAll();
        List<CookingMenu> ll = new ArrayList<>();
        for (CookingMenu cookingMenu : temp) {
            if (cookingMenu.getUploaded() == 0) {
                ll.add(cookingMenu);
            }
        }
        return ll;
    }

    private List<CookingMenu> getMenu(int flag) {
        List<CookingMenu> temp = cookingMenuDao.queryForAll();
        List<CookingMenu> ll = new ArrayList<>();
        for (CookingMenu cookingMenu : temp) {
            if (cookingMenu.getType() == flag) {
                ll.add(cookingMenu);
            }
        }
        return ll;
    }

    @Override
    public void selectResult(int value, int id) {
        try {
            if (value == 1 && cookingMenuDao != null) {
                if (adapter.getData() == null || adapter.getData().isEmpty()) {
                    showShortToast("没有数据可以删除");
                    return;
                }
                if (loadingDialog == null) {
                    loadingDialog = new LoadingDialog(this, "正在删除数据...");
                }
                deleteInfo(adapter.getData());
            }
        } catch (Exception e) {
            showLongToast("删除失败:" + e.getMessage());
        }
    }

    private void deleteInfo(final List<CookingMenu> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        loadingDialog.show("正在删除..." + 0);
        total = list.size();
        ThreadPoolExecutorHelper.getInstance().getScheduledThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                int current=0;
                try {
                    for (int i = 0; i < list.size(); i++) {
                        cookingMenuDao.delete(list.get(i));
                        current++;
                        showLoadMsg("删除进度:"+current+"/"+total);
                    }
                }catch (Exception e){

                }
            }
        });
    }

    private void showLoadMsg(final String s) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                loadingDialog.setMsg(s);
            }
        });
    }
}